What is import-lazy?
The import-lazy npm package allows for lazy-loading of modules in Node.js. This means that modules are only loaded when they are actually used in the code, which can significantly improve the startup time of applications by reducing the initial load time.
What are import-lazy's main functionalities?
Lazy-loading of CommonJS modules
This feature allows you to lazy-load CommonJS modules. The module is only loaded when a method of the module is called, as demonstrated with the lodash library.
const importLazy = require('import-lazy')(require);
const _ = importLazy('lodash');
console.log(_.isString('hello'));
Lazy-loading of ES Modules
This feature supports lazy-loading of ES Modules. Similar to the CommonJS example, the ES Module is loaded only when a method is invoked.
import importLazy from 'import-lazy';
const _ = importLazy(() => import('lodash-es'));
console.log(_.isString('hello'));
Other packages similar to import-lazy
p-lazy
p-lazy is a package that allows for creating lazy promises that are only executed when awaited. While import-lazy is focused on lazy-loading modules, p-lazy deals with the execution of asynchronous operations, making them conceptually similar but functionally different.
lazy-require
lazy-require offers functionality similar to import-lazy by allowing deferred loading of modules. The main difference is in the implementation details and API design, where lazy-require might offer different or additional options for managing module caching and re-loading.
import-lazy
Import a module lazily
Install
$ npm install import-lazy
Usage
const importLazy = require('import-lazy')(require);
const _ = importLazy('lodash');
_.isNumber(2);
_.isNumber('unicorn');
const stuff = importLazy('./math-lib');
console.log(stuff.sum(1, 2));
console.log(stuff.PHI);
Warning: Destructuring will cause it to fetch eagerly
While you may be tempted to do leverage destructuring, like this:
const {isNumber, isString} = importLazy('lodash');
Note that this will cause immediate property access, negating the lazy loading, and is equivalent to:
import {isNumber, isString} from 'lodash';
Related
- resolve-from - Resolve the path of a module from a given path
- import-from - Import a module from a given path
- resolve-pkg - Resolve the path of a package regardless of it having an entry point
- lazy-value - Create a lazily evaluated value
- define-lazy-prop - Define a lazily evaluated property on an object
License
MIT © Sindre Sorhus